import CanvasMap from "./CanvasMap";
import { random } from "./tools.js";

/**
 * 最基础的生命。只会随机游荡。随机吃身边比自己能量少的同类。不会躲避。每个随机刻有1/2的概率分裂。通过摄入设备的电量来获得用于繁殖的能量
 */
export default class Animal{
    x=50;
    y=50;
    id=0;
    /**
     * 年龄
     */
    age=0;
    power=256;
    /**
     * 捕猎意愿
     */
    wantEat=7;
    /**
     * 繁殖意愿
     */
    wantbreed=7;
    /**
     * 就地获得能量意愿
     */
    wantsun=7;
    /**
     * 移动意愿
     */
    wantmove=7;
    /**
     * 后代基因变异的概率
     */
    wantChange=7;
    constructor(config:AnimalConfig){
        this.x=config.x;
        this.y=config.y
        this.id=config.id||0;
        this.power=config.power||100;
        this.wantEat=config.wantEat||7
        this.wantbreed=config.wantbreed||7;
        this.wantsun==config.wantsun||7;
        this.wantmove==config.wantmove||7;
    }
    breed (env:CanvasMap,x:number,y:number){
        env.create(new Animal({x,y}),this);
    }
    /**
     * 从自然界获得能量
     * @param env 
     */
    getPowerFromNature(env:CanvasMap){
        env.getPowerFromNature(this);
    }
    /**
     * 移动
     * @param x 
     * @param y 
     */
    move(env:CanvasMap,x:number,y:number){
        if(this.power){
            let success=env.animalMove(this.x,this.y,x,y);
            if(success){
                this.x=x;
                this.y=y;
            }
        }
    }
    run(env:CanvasMap){
        let nx=this.x+random(2)-1;
        let ny=this.y+random(2)-1;
        let tpr=this.wantEat+this.wantbreed+this.wantsun+this.wantmove;
        let MySelect=random(tpr);
        let options=0;
        if(this.wantEat&&MySelect<this.wantEat){
            if(env.checkHaslife(nx,ny)){
                this.tryEat(env,nx,ny);
            }
        }
        options+=this.wantEat
        if(this.wantbreed&& MySelect>=options&&MySelect<options+this.wantbreed){
            if(!env.checkHaslife(nx,ny)){
                this.breed(env,nx,ny);
            }
        }
        options+=this.wantbreed
        if(this.wantsun&& MySelect>=options&&MySelect<options+this.wantsun){
            this.getPowerFromNature(env);
        }
        options+=this.wantsun
        if(this.wantmove&& MySelect>=options&&MySelect<options+this.wantmove){
            this.move(env,nx,ny);
        }
    }
    toObject(){
        return {
            x:this.x,
            y:this.y,
            id:this.id,
            power:this.power,
            wantEat:this.wantEat,
            wantbreed:this.wantbreed,
            wantsun:this.wantsun,
            wantmove:this.wantmove,
        }
    }
    toJSON(){
        return this.toObject();
    }
    tryEat(env:CanvasMap,x:number,y:number){
        return env.tryEat(this,x,y);
    }
}
export interface AnimalConfig{
    x:number,
    y:number
    id?:number,
    power?:number,
    wantEat?:number,
    wantbreed?:number,
    wantsun?:number,
    wantmove?:number,

    age?:number
    wantChange?:number
}